import config from '@/config';
import axios from 'axios'
import { setToken,getToken } from '@/utils/tool';
import router from '@/router'
import { Message,Loading  } from 'element-ui';
const baseURL = process.env.NODE_ENV !== 'production' ? config.baseUrl.dev : config.baseUrl.pro;

let loading;
function startLoading() {
    loading = Loading.service({
        lock: true,
        text: '正在玩命加载中……',
        background: 'rgba(162,162,162, 0.8)'
    })
}
function endLoading() {
    loading.close()
}


class HttpRequest {
    constructor(baseUrl = baseURL){
        this.baseUrl = baseUrl;
        this.queue = {};
    }

    getInSideConfig(){
        const config = {
            baseURL:this.baseUrl,
            timeout:200000,
            headers:{
                "token": getToken()
            }
        };
        return config;
    }

    interceptors(instance,url){
        instance.interceptors.request.use(config=>{
            if(!Object.keys(this.queue).length){
                startLoading();
            }
            this.queue[url] = true;
            return config;
        },
        error=>{
            return Promise.reject("请求前出现错误,错误是:"+error);
        });

        instance.interceptors.response.use(res=>{
            endLoading();
            if(res.data.code == '101'){
                Message.warning({message:'登录超时,请重新登录',center:true});
                setToken('');
                router.push({ name:'login' });
                return false;
            }
            if(res.data.code != '101' && res.data.message != "" ){
                Message({
                    type:res.data.success ? 'success':"error",
                    message:res.data.message,
                    center:true
                });
            }


            if(res.status == 500){
                Message.warning({message:'您的网络不稳定, 请稍后再试...',center:true});
                setToken('');
                router.push({ name:'login' });
                return false;
            }
            delete this.queue[url];
            return res;
        },
        error=>{
            delete this.queue[url];
            return Promise.reject("请求后出现错误,错误是:"+error);
        });
    }

    request(options){
        const instance = axios.create();
        options = Object.assign(this.getInSideConfig(),options);
        this.interceptors(instance,options.url);
        return instance(options);
    }
}

export default HttpRequest;

